# -*- coding: utf-8 -*-
import requests,json,os,urllib,string,sys
import scrapy
from S00.sqlHelper import *

reload(sys)
sys.setdefaultencoding('utf8')

class ZqSpider(scrapy.Spider):
    name = 'zq'
    allowed_domains = ['500.com']
    offset=1
    num=0
    url='http://liansai.500.com/team/'
    start_urls = [url+str(offset)]
    DOWNLOAD_DELAY=0.1
    def parse(self, response):
        for each in response.xpath("//div[@class='itm_logo']"):
            try:
                cn=each.xpath("./img/@alt").extract()[0]
                en=each.xpath("./div/div/text()").extract()[0]
                url = each.xpath("./img/@src").extract()[0]
                fn=en+url[len(url)-4:]
                if en[0:1]==' ':
                    en=en[1:len(en)]
                if url!="http://www.500cache.com/liansai/images/500logo.png":
                    self.save_data(en,cn,en+fn)
                    self.save_img(url,en)
                else:
                    self.save_data(en,cn,'')
                    if os.path.exists('zq/'+fn):
                        os.remove(fn)
            except Exception,e:
                traceback.print_exc()
                print str(self.offset)+'不存在'

        if self.offset < 10623:
            self.offset += 1
        yield scrapy.Request(self.url+str(self.offset), callback = self.parse)

    def save_data(self,en,cn,logo):
        if sqlHelper.selectOne("select id from team where cn=%s and typeText=%s",(cn,'足球')):
            if sqlHelper.update("UPDATE team SET source=%s,en=%s WHERE cn=(SELECT cn FROM (SELECT * FROM team WHERE en='' and cn=%s and typeText=%s) AS t)",(self.url+str(self.offset),en,cn,'足球')):
                print '更新'+cn+'--en>>'+en
#            if sqlHelper.update("UPDATE team SET source=%s,big=%s WHERE cn=(SELECT cn FROM (SELECT * FROM team WHERE big='' and cn=%s and typeText=%s) AS t)",(self.url+str(self.offset),big,cn,'足球')):
#                print '更新'+cn+'--big>>'+big
            if sqlHelper.update("UPDATE team SET source=%s,logo=%s WHERE cn=(SELECT cn FROM (SELECT * FROM team WHERE logo='' and cn=%s and typeText=%s) AS t)",(self.url+str(self.offset),logo,cn,'足球')):
                print '更新'+cn+'--logo>>'+logo
            return False
        sqlHelper.update("insert into team(type,cn,en,logo,source) values(%s,%s,%s,%s)",('足球',cn,en,logo,self.url+str(self.offset)))
        self.num+=1
        print cn
        return True
    
    def save_img(self,img_url,file_name,file_path='zq'):
        img_url=img_url.replace('\/','/')
        try:
            if not os.path.exists(file_path):
                print '文件夹',file_path,'不存在，重新建立'
                os.makedirs(file_path)
            #获得图片后缀
            file_suffix = os.path.splitext(img_url)[1]
            #拼接图片名（包含路径）
            filename = '{}{}{}{}'.format(file_path,os.sep,file_name,file_suffix)
            filename=filename.replace('.com','_com')
            if string.find(filename,'.')==-1:
                filename=filename+'.png'
            if string.find(filename,'?')!=-1:
                filename=filename[0:len(filename)-4]
#       m下载图片，并保存到文件夹中
            urllib.urlretrieve(img_url,filename=filename)
        except IOError as e:
            print '文件操作失败',e
        except Exception as e:
            print '错误 ：',e
    def close(self,reason):
        print "采集完成,共采集了["+str(self.num)+"]条数据"
